package cn.org.timespace.easyframe.util.web;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class Security {

	public static String hasString(byte[] b) {
		String has = "", tmp = "";
		for (int i = 0; i < b.length; i++) {
			tmp = (java.lang.Integer.toHexString(b[i] & 0XFF));
			if (tmp.length() == 1)
				has = has + "0" + tmp;
			else
				has = has + tmp;
			if (i < b.length - 1)
				has = has + ":";
		}
		return has.toUpperCase();
	}

	// 加密
	public static String encrypt(String plainText) {
		MessageDigest md;
		byte[] b = null;
		
		try {
			md = MessageDigest.getInstance("MD5");
			md.update(plainText.getBytes());
			
			b = md.digest();
			
			System.out.println("-------:"+b);
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		
		return hasString(b);
	}
	//转byte
	public static String turnHasString(String plainText) {
		
		String result = "";
		try {
			
			int lg = plainText.length();
			for(int i=0;i<lg;i=i+2){
				result +=plainText.toUpperCase().substring(i, i+2);
				if(i<lg-2){
					result+=":";
				}
			}
			
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return result;
	}

	// 验证
	public static boolean verify(String plainText, String encryptStr){
		return (encrypt(plainText).equals(encryptStr));
	}
	
	 public static String getMD5Str(String str) {  
         MessageDigest messageDigest = null;  
  
        try {  
             messageDigest = MessageDigest.getInstance("MD5");  
  
             messageDigest.reset();  
  
             messageDigest.update(str.getBytes("UTF-8"));  
         } catch (NoSuchAlgorithmException e) {  
             System.out.println("NoSuchAlgorithmException caught!");  
             System.exit(-1);  
         } catch (UnsupportedEncodingException e) {  
             e.printStackTrace();  
         }  
  
        byte[] byteArray = messageDigest.digest();  
  
         StringBuffer md5StrBuff = new StringBuffer();  
  
        for (int i = 0; i < byteArray.length; i++) {              
            if (Integer.toHexString(0xFF & byteArray[i]).length() == 1)  
                 md5StrBuff.append("0").append(Integer.toHexString(0xFF & byteArray[i]));  
            else  
                 md5StrBuff.append(Integer.toHexString(0xFF & byteArray[i]));  
         }  
  
        return md5StrBuff.toString();  
     }       
	
	public static void main(String args[]){
		
		System.out.println(turnHasString("202cb962ac59075b964b07152d234b70"));
		System.out.println(getMD5Str("123"));
	}
}
